package com.cmcc.cmii.smspush.wechat.mytest;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;

import java.util.ArrayList;
import java.util.List;
@Slf4j
public class WechatApiTest {

    public static void main(String[] args) throws Exception{
        WxMpService wxMpService = new WxMpServiceImpl();
        WxMpDefaultConfigImpl wxStorage = new WxMpDefaultConfigImpl();
        wxStorage.setAppId("wxb9ed925bae5391f2");//appid
        wxStorage.setSecret("1c869cfc40f313a45b5fe096865a20e9");
        wxMpService.setWxMpConfigStorage(wxStorage);
        WxMpUserService userService = wxMpService.getUserService();
        WxMpUserList wxMpUserList = userService.userList(null);

        List<WxMpUser> userList = getWxMpUserList(userService, wxMpUserList.getOpenids());
        System.out.println(userList);

        //客户消息
       // sendMessage(wxMpService);

        //群发消息
        //openIdsSend(wxMpService,userList);

        //发送图片
        sendPicMessage(wxMpService);

    }

    private static void sendPicMessage(WxMpService wxMpService) throws Exception{
        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setMsgType(WxConsts.KefuMsgType.IMAGE);
        message.setToUser("ofHUhwBW0ojZLZhhadK1y7TOvMD4");
        message.setTitle("测试信息");
        message.setMediaId("x75hoZlnL2S0kfNdYK83FpT9H0hPGjgtv1GdPKaVn5Hs72bPqVn5cLJBnIOEAA0x");
        boolean result = wxMpService.getKefuService().sendKefuMessage(message);
    }

    /**
     * 测试群发消息
     * @param wxMpService
     */
    private static void openIdsSend(WxMpService wxMpService,List<WxMpUser> userList) throws Exception{
        WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
        massMessage.setMsgType(WxConsts.MassMsgType.TEXT);
        massMessage.setContent("测试群发消息\n欢迎欢迎，热烈欢迎\n换行测试");
        List<String> openIds = new ArrayList<>();
        userList.forEach(wxMpUser -> {
            String openId = wxMpUser.getOpenId();
            openIds.add(openId);
        });
        massMessage.getToUsers().addAll(openIds);
        massMessage.getToUsers().addAll(openIds);
        wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);

    }

    /**
     * 指定用户发送图文消息
     * @param wxMpService
     * @throws Exception
     */
    private static void sendMessage(WxMpService wxMpService) throws Exception{
        WxMpKefuMessage.WxArticle article1 = new WxMpKefuMessage.WxArticle();
        article1.setUrl("http://xial9527.w3.luyouxia.net/wx/jsp/login.html");
        article1.setPicUrl("http://test.iwocloud.com/wx/images/index_bg.png");
        article1.setDescription("今天天气很好，适合出去玩");
        article1.setTitle("测试测试测试一下啦啦啦");
        // 图文消息2
        WxMpKefuMessage.WxArticle article2 = new WxMpKefuMessage.WxArticle();
        article2.setUrl("http://xial9527.w3.luyouxia.net/wx/index?code=1YF00137");
        article2.setPicUrl("http://test.iwocloud.com/wx/images/index_bg.png");
        article2.setDescription("晚上去吃火锅吧，逛超市");
        article2.setTitle("今日安排");

        List<WxMpKefuMessage.WxArticle> articles = new ArrayList<>();
        articles.add(article1);
        //articles.add(article2);
        WxMpKefuMessage wxMpKefuMessage = WxMpKefuMessage.NEWS().toUser("ofHUhwBW0ojZLZhhadK1y7TOvMD4").articles(articles).build();
        wxMpService.getKefuService().sendKefuMessage(wxMpKefuMessage);
    }


    /**
     * 分批次获取微信粉丝信息 每批100条
     * @param wxMpUserService
     * @param openidsList
     * @return
     * @throws WxErrorException
     * @author
     */
    private static List<WxMpUser> getWxMpUserList(WxMpUserService wxMpUserService, List<String> openidsList) throws WxErrorException {
        // 粉丝openid数量
        int count = openidsList.size();
        if (count <= 0) {
            return new ArrayList<>();
        }
        List<WxMpUser> list = Lists.newArrayList();
        List<WxMpUser> followersInfoList;
        int a = count % 100 > 0 ? count / 100 + 1 : count / 100;
        for (int i = 0; i < a; i++) {
            if (i + 1 < a) {
                log.debug("i:{},from:{},to:{}", i, i * 100, (i + 1) * 100);
                followersInfoList = wxMpUserService.userInfoList(openidsList.subList(i * 100, ((i + 1) * 100)));
                if (null != followersInfoList && !followersInfoList.isEmpty()) {
                    list.addAll(followersInfoList);
                }
            }
            else {
                log.debug("i:{},from:{},to:{}", i, i * 100, count - i * 100);
                followersInfoList = wxMpUserService.userInfoList(openidsList.subList(i * 100, count));
                if (null != followersInfoList && !followersInfoList.isEmpty()) {
                    list.addAll(followersInfoList);
                }
            }
        }
        log.debug("本批次获取微信粉丝数：",list.size());
        return list;
    }
}
